package com.trinity.sample

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.preference.PreferenceManager
import com.timqi.sectorprogressview.ColorfulRingProgressView
import com.trinity.core.TrinityCore
import com.trinity.editor.VideoExport
import com.trinity.editor.VideoExportInfo
import com.trinity.listener.OnExportListener
import com.trinity.sample.tool.WkLogTool
import java.io.File


class VideoExportActivity : AppCompatActivity(), OnExportListener {
  private lateinit var mProgressBar: ColorfulRingProgressView
  private lateinit var mVideoView: VideoView
  private lateinit var exportInfo :TextView
  private lateinit var mContext :Context

  /**
   * 视屏导出类
   */
  private lateinit var mVideoExport: VideoExport

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_video_export)

    mContext = this
    mProgressBar = findViewById(R.id.progress_view)
    mVideoView = findViewById(R.id.video_view)
    exportInfo = findViewById(R.id.exportInfo)

    findViewById<View>(R.id.goBack).setOnClickListener{

      (mContext as Activity).finish()

    }

    mVideoView.setOnPreparedListener {
      it.isLooping = true
    }

    val preferences = PreferenceManager.getDefaultSharedPreferences(this)
    val softCodecEncode = preferences.getBoolean("export_soft_encode", false)
    val softCodecDecode = preferences.getBoolean("export_soft_decode", false)
    val info = VideoExportInfo("/sdcard/export.mp4")
    info.mediaCodecDecode = !softCodecDecode
    info.mediaCodecEncode = !softCodecEncode

    val width = resources.displayMetrics.widthPixels
    val params = mVideoView.layoutParams as ConstraintLayout.LayoutParams
    params.width = width
    params.height = ((width * (info.height * 1.0f / info.width)).toInt())
    mVideoView.layoutParams = params
    mVideoExport = TrinityCore.createExport(this)
    mVideoExport.export(info, this)
  }

  override fun onExportProgress(progress: Float) {
    mProgressBar.percent = progress * 100
    WkLogTool.showLog("onExportProgress="+ mProgressBar.percent )
    exportInfo.text= (progress * 100).toString()
  }

  override fun onExportFailed(error: Int) {
    exportInfo.text= "导出失败。"+ error
  }

  override fun onExportCanceled() {
    val file = File("/sdcard/export.mp4")
    file.delete()
  }

  override fun onExportComplete() {
    exportInfo.text= "导出完成。/sdcard/export.mp4"
    mProgressBar.visibility = View.GONE
    mVideoView.setVideoPath("/sdcard/export.mp4")
    mVideoView.start()
  }

  override fun onDestroy() {
    super.onDestroy()
    mVideoExport.cancel()
  }
}


